<template>
  <div>
    <el-card>
      <!-- 搜索 -->
      <div class="search">
        <el-input
          class="input"
          v-model.trim="searchKeyword"
          @keyup.native.enter="getUserList(undefined, 1)"
        ></el-input>
        <el-button
          type="primary"
          icon="el-icon-sheach"
          @click="getUserList(undefined, 1)"
          >查询</el-button
        >
        <el-button @click="clearSearch">清空</el-button>
      </div>
      <div>
        <el-button type="primary" @click="userFormDialog = true"
          >添加用户</el-button
        >
        <el-button
          type="danger"
          :disabled="delIdList.length == 0"
          @click="delUserList"
          >批量删除</el-button
        >
      </div>
      <!-- 表格 -->
      <div>
        <el-table
          border
          :data="userList"
          :height="tableHeigth||undefined"
          @selection-change="selectTable"
        >
          <el-table-column
            type="selection"
            align="center"
            label="选择"
          ></el-table-column>
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <!-- <el-table-column label="头像" width="70" align="center">
            <template #default="{ row }">
              <img
                :src="row.headImg"
                style="
                  height: 50px;
                  width: 50px;
                  object-fit: contain;
                  border-radius: 50%;
                "
              />
            </template>
          </el-table-column> -->
          <el-table-column label="用户名" prop="username"></el-table-column>
          <el-table-column label="用户昵称" prop="nickName"></el-table-column>
          <el-table-column label="角色列表" prop="roleName"> </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="info"
                icon="el-icon-user-solid"
                title="修改用户所属角色"
                @click="editUserRoleList(row)"
              ></el-button>
              <el-button
                size="mini"
                type="warning"
                @click="clickUpuserInfo(row)"
                >修改</el-button
              >
              <el-popconfirm
                class="popconfirm"
                title="确定删除吗"
                @onConfirm="delUserInfo(row.id)"
              >
                <template #reference>
                  <el-button size="mini" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column width="50" align="center">
            <template #header>
              <div
                title="取消固定表头"
                v-if="isfixedHeader"
                @click="isfixedHeader = false"
              >
                <svg
                  t="1668593907681"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="2704"
                  width="18"
                  height="18"
                >
                  <path
                    d="M547.1 889.4L134.3 476.6c-15.8-15.8-3.9-42.9 18.5-41.8l118.6 5.6 311.9-207.9 5.5-92.8c1.2-21.1 26.8-30.8 41.8-15.9l269.3 269.3c14.9 14.9 5.2 40.5-15.9 41.8l-92.8 5.5-207.9 311.9 5.6 118.6c1.1 22.4-25.9 34.3-41.8 18.5z"
                    fill="#EF5343"
                    p-id="2705"
                  ></path>
                  <path
                    d="M354.6 470.9c-4 0-7.8-1.9-10.2-5.5-3.8-5.6-2.2-13.2 3.4-17l190-126.7c5.6-3.8 13.2-2.2 17 3.4 3.8 5.6 2.2 13.2-3.4 17l-190 126.7c-2.1 1.4-4.5 2.1-6.8 2.1z"
                    fill="#FFFFFF"
                    p-id="2706"
                  ></path>
                  <path
                    d="M899.9 393.2l-61.3-61.3c14.9 14.9 5.2 40.5-15.9 41.8l-92.8 5.5L522 691l5.6 118.6c1.1 22.4-26 34.3-41.8 18.5l61.3 61.3c15.8 15.8 42.9 3.9 41.8-18.5l-5.6-118.6 207.9-311.9L884 435c21.1-1.3 30.8-26.9 15.9-41.8z"
                    fill="#D84141"
                    p-id="2707"
                  ></path>
                  <path
                    d="M587.3 307.7m-12.3 0a12.3 12.3 0 1 0 24.6 0 12.3 12.3 0 1 0-24.6 0Z"
                    fill="#FFFFFF"
                    p-id="2708"
                  ></path>
                  <path
                    d="M912.9 380.2L643.5 110.9c-12.1-12.1-29.6-15.8-45.6-9.8s-26.6 20.5-27.6 37.6l-4.9 83.7-299.1 199.4-112.6-5.4c-17.8-0.7-34 9.2-41.3 25.5s-3.7 35 8.9 47.7L314.7 683 102.5 895.2c-7.2 7.2-7.2 18.8 0 26 3.6 3.6 8.3 5.4 13 5.4s9.4-1.8 13-5.4L340.7 709l193.4 193.4c8.3 8.3 19.1 12.6 30.2 12.6 5.9 0 11.8-1.2 17.4-3.7 16.3-7.2 26.3-23.4 25.5-41.3l-5.4-112.6 199.5-299.2 83.7-4.9c17.1-1 31.5-11.6 37.6-27.6s2.4-33.4-9.7-45.5z m-24.6 32.5c-0.5 1.4-1.9 3.7-5.4 3.9l-85.2 5-135.3-135.3c-7.2-7.2-18.8-7.2-26 0-7.2 7.2-7.2 18.8 0 26l130.9 130.9-187.5 281.2-223.7-223.7c-7.2-7.2-18.8-7.2-26 0-7.2 7.2-7.2 18.8 0 26l225.1 225.1c2.8 2.8 6.3 4.5 9.9 5.1l5.5 114.9c0.2 3.5-1.9 5.1-3.6 5.9-1.7 0.8-4.4 1.2-6.8-1.3L147.3 463.6c-2.5-2.5-2-5.1-1.3-6.8 0.8-1.7 2.5-4 5.9-3.6l118.6 5.6c3.9 0.2 7.8-0.9 11.1-3.1l311.9-207.9c4.8-3.2 7.8-8.5 8.2-14.2l5.5-92.8c0.2-3.5 2.6-4.8 3.9-5.4 1.4-0.5 4.1-1 6.5 1.4l269.3 269.3c2.4 2.5 1.9 5.2 1.4 6.6z"
                    fill="#2D3742"
                    p-id="2709"
                  ></path>
                </svg>
              </div>
              <div title="固定表头" v-else @click="isfixedHeader = true">
                <svg
                  t="1668594485297"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="3516"
                  width="20"
                  height="20"
                >
                  <path
                    d="M474.6 246.7H592V452H474.6zM722.3 596.9C720 536.5 642.5 488 547.2 488s-172.8 48.5-175.1 108.9h350.2zM665.8 192.5H389.2c-9.9 0-18-8.1-18-18s8.1-18 18-18h276.6c9.9 0 18 8.1 18 18s-8.1 18-18 18z"
                    fill="#25B195"
                    p-id="3517"
                  ></path>
                  <path
                    d="M658.2 206.5H359.9c-25.8 0-46.9-21-46.9-46.9s21-46.9 46.9-46.9h298.4c25.8 0 46.9 21 46.9 46.9s-21.1 46.9-47 46.9z m-298.3-63.6c-9.2 0-16.7 7.5-16.7 16.7s7.5 16.7 16.7 16.7h298.4c9.2 0 16.7-7.5 16.7-16.7s-7.5-16.7-16.7-16.7H359.9zM512.3 909l-46.6-303.6h86.7z"
                    fill="#4E4D4D"
                    p-id="3518"
                  ></path>
                  <path
                    d="M667.8 484.8c-17.2-13.1-36.6-23.9-57.6-32H407.9c-21 8.2-40.4 18.9-57.6 32-21.3 16.3-38.2 35.4-50.1 56.9-12.7 23-19.2 47.6-19.2 73.1v17.9h456.1v-17.9c0-25.5-6.5-50.1-19.2-73.1-11.9-21.5-28.7-40.6-50.1-56.9zM312.7 596.9c5.3-30.6 24-59.2 53.9-82.1C404.5 485.9 455 470 509.1 470c54 0 104.6 15.9 142.4 44.8 30 22.9 48.7 51.6 53.9 82.1H312.7z"
                    fill="#4E4D4D"
                    p-id="3519"
                  ></path>
                  <path
                    d="M607 468H409V181h198v287z m-161.6-35.5h125.1v-216H445.4v216z"
                    fill="#4E4D4D"
                    p-id="3520"
                  ></path>
                </svg>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @current-change="getUserList(undefined, $event)"
          @size-change="getUserList(undefined, undefined, $event)"
          :current-page="curPage"
          layout="sizes, prev, pager, next, jumper, ->, total, slot"
          :page-sizes="[10, 20, 30]"
          :page-size="pageLimit"
          :total="totalPage"
        ></el-pagination>
      </div>
      <!-- 添加用户 -->
      <div>
        <el-dialog :visible.sync="userFormDialog" @closed="closeDialog">
          <el-form
            ref="userForm"
            :model="userForm"
            label-width="80px"
            :rules="formRules"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model.trim="userForm.username"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model.trim="userForm.nickName"></el-input>
            </el-form-item>
            <el-form-item
              label="密码"
              :prop="prop_password"
              v-show="!userForm.id"
            >
              <el-input
                v-model.trim="userForm.password"
                :validate-event="!userForm.id"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <div class="right">
                <el-button type="primary" @click="addOrupdataUserInfo"
                  >保存</el-button
                >
                <el-button @click="userFormDialog = false">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 编辑用户所属角色 -->
      <el-dialog
        :visible.sync="userRoleFormDialog"
        title="编辑用户所属角色"
        @closed="closeUserRoleDialog"
      >
        <el-form>
          <el-form-item label="用户名">
            <el-input :disabled="true" :value="userRoleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="用户角色">
            <div>
              <el-checkbox
                v-model="checkAll"
                @change="handleCheckAllChange"
                :indeterminate="isIndeterminate"
                >全选</el-checkbox
              >
              <div style="margin: 15px 0"></div>
              <el-checkbox-group
                v-model="userRoleForm.roleList"
                @change="handleCheckedChange"
              >
                <el-checkbox
                  v-for="item in allRolesList"
                  :label="item.id"
                  :key="item.id"
                  :checked="item.checked"
                  >{{ item.roleName }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="right">
              <el-button type="primary" @click="updataUserRoleList"
                >保存</el-button
              ><el-button @click="userRoleFormDialog = false">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 固定表头
      isfixedHeader: false,
      // 用户角色编辑
      isIndeterminate: true,
      checkAll: false,
      allRolesList: [],
      userRoleForm: { name: '', roleList: [], id: '' },
      userRoleFormDialog: false,
      //
      delIdList: [],
      searchKeyword: '',
      // 用户信息表单
      userFormDialog: false,
      formRules: {
        username: [
          { required: true, min: 2, max: 10, message: '长度在2到10之间' }
        ],
        nickName: [
          { required: true, min: 2, max: 10, message: '长度在2到10之间' }
        ],
        password: [
          { required: true, min: 4, max: 16, message: '长度在2到16之间' }
        ]
      },
      userForm: {
        id: undefined,
        username: '',
        nickName: '',
        password: ''
      },
      // 用户列表
      userListInfo: {},
      // 分页
      curPage: 1,
      pageLimit: 10
    }
  },
  computed: {
    totalPage() {
      return this.userListInfo.total || 0
    },
    userList() {
      if (this.userListInfo.items) {
        return this.userListInfo.items.filter(
          (item) => item.username != 'admin'
        )
      } else return []
    },
    prop_password() {
      return this.userForm.id ? '' : 'password'
    },
    tableHeigth(){
      return this.isfixedHeader?'65vh':''
    }
  },
  methods: {
    // 保存用户所属角色
    async updataUserRoleList() {
      const { userRoleForm } = this
      const { id, roleList } = userRoleForm
      const res = await this.$API.user.updataUserRoleList(id, roleList)

      if ([200, 20000, '20000', '200'].includes(res.code)) {
        this.$message({ type: 'success', message: '修改成功' })
        // 跟新数据
        this.getUserList()
        // 关闭对话框
        this.userRoleFormDialog = false
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 清空用户所属角色数据
    closeUserRoleDialog() {
      this.userRoleForm.name = ''
      // 重要
      /* 因为 
       <el-checkbox-group
        v-model="userRoleForm.roleList"
      */
      this.userRoleForm.roleList = []
      this.allRolesList = []
    },
    handleCheckedChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.allRolesList.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRolesList.length
    },
    // 全选,取消全选
    handleCheckAllChange(val) {
      const { allRolesList, userRoleForm } = this
      userRoleForm.roleList = []
      if (val) {
        allRolesList.forEach((item) => {
          userRoleForm.roleList.push(item.id)
        })
      }
      this.isIndeterminate = false
    },
    // 编辑用户所属角色
    async editUserRoleList(row) {
      // 获取用户列表
      const res = await this.$API.user.getUseroleList(row.id)
      if ([200, 20000].includes(res.code)) {
        res.data.assignRoles.forEach((item) => {
          for (let i = 0; i < res.data.allRolesList.length; i++) {
            if (res.data.allRolesList[i].id == item.id) {
              res.data.allRolesList[i]['checked'] = true

              break
            }
          }
        })
        this.allRolesList = res.data.allRolesList
        this.userRoleForm.id = row.id
        this.userRoleForm.name = row.username
        // 显示表单
        this.userRoleFormDialog = true
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },

    closeDialog() {
      // 清除数据
      // this.$refs.userForm.resetFields()
      // 会恢复到userForm 初始值,并不是真的的清空
      // 如果 userForm 被赋值为用户要修改的数据,则resetFields()以后只是恢复到了初始数据

      this.clearForm()
    },
    clearForm() {
      this.userForm = {
        id: undefined,
        username: '',
        nickName: '',
        password: ''
      }
    },
    // 点击跟新
    clickUpuserInfo(row) {
      this.userForm = JSON.parse(JSON.stringify(row))
      this.userFormDialog = true
    },
    selectTable(list) {
      // 先清空
      this.delIdList = []
      list.forEach((item) => {
        this.delIdList.push(item.id)
      })
    },
    // 批量删除
    delUserList() {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          const { delIdList } = this
          if (delIdList.length != 0) {
            const res = await this.$API.user.deluserList(delIdList)
            if ([200, 20000].includes(res.code)) {
              this.$message({ type: 'success', message: '删除成功' })
              // 跟新
              this.getUserList()
            } else {
              this.$message({
                type: 'error',
                message: res.message + ':' + (res.data || '')
              })
            }
          } else {
          }
        })
        .catch(() => {})
    },
    // 删除用户
    async delUserInfo(id) {
      const res = await this.$API.user.delUserInfo(id)
      if ([200, 20000].includes(res.code)) {
        this.$message({ type: 'success', message: '删除成功' })
        // 跟新
        this.getUserList()
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    clearSearch() {
      this.searchKeyword = ''
      this.getUserList(undefined, 1)
    },
    // 添加或跟新用户
    addOrupdataUserInfo() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          const { userForm } = this
          const res = await this.$API.user.addOrupdataUserInfo(userForm)
          if ([200, 20000].includes(res.code)) {
            this.$message({
              type: 'success',
              message: userForm.id ? '修改成功' : '添加成功'
            })
            // 跟新
            this.getUserList()
          } else {
            this.$message({
              type: 'error',
              message: res.message + ':' + (res.data || '')
            })
          }

          this.userFormDialog = false
        } else {
          this.$message({ type: 'warning', message: '请完整填写信息' })
        }
      })
    },

    // 获取用户列表
    async getUserList($event, page, limit) {
      if (page) {
        this.curPage = page
      }
      if (limit) {
        this.pageLimit = limit
      }

      const res = await this.$API.user.getUserList(
        this.curPage,
        this.pageLimit,
        this.searchKeyword
      )
      if (res.code == 200 || res.code == 20000) {
        this.userListInfo = res.data
      } else {
      }
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style lang="scss" scoped>
.search {
  margin: 10px 0;
}
.input {
  width: 40% !important;
}
.pagination {
  text-align: center;
}

.center {
  text-align: center;
}
.right {
  position: absolute;
  right: 0px;
}
.popconfirm {
  margin-left: 10px;
}
</style>
